{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   Pregnancies  Glucose  BloodPressure  SkinThickness  Insulin   BMI  DiabetesPedigreeFunction  Age  Outcome\n",
      "0            6      148             72             35        0  33.6                     0.627   50        1\n",
      "1            1       85             66             29        0  26.6                     0.351   31        0\n",
      "2            8      183             64              0        0  23.3                     0.672   32        1\n",
      "3            1       89             66             23       94  28.1                     0.167   21        0\n",
      "4            0      137             40             35      168  43.1                     2.288   33        1\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "from sklearn.preprocessing import StandardScaler\n",
    "from sklearn.ensemble import RandomForestClassifier\n",
    "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.tree import DecisionTreeClassifier\n",
    "from sklearn.linear_model import LogisticRegression\n",
    "from sklearn.neighbors import KNeighborsClassifier\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "from sklearn.neural_network import MLPClassifier\n",
    "from xgboost import XGBClassifier\n",
    "from sklearn.svm import SVC\n",
    "\n",
    "pd.set_option('display.max_rows', 10)\n",
    "pd.set_option('display.max_columns', 10)\n",
    "pd.set_option('display.width', 1000)\n",
    "\n",
    "#   导入csv数据\n",
    "df = pd.read_csv(\"C:/Users/yc/Desktop/diabetes2.csv\")\n",
    "df=df.loc[:, ~df.columns.str.contains('^Unnamed')]\n",
    "print(df.head())\n",
    "\n",
    "#   x为可能导致糖尿病的因素\n",
    "x = df.drop('Outcome', axis=1)\n",
    "#   y为诊断结果，1为确诊，2为未确诊\n",
    "y = df['Outcome']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Requirement already satisfied: xgboost in c:\\users\\yc\\anaconda3\\lib\\site-packages (1.6.1)\n",
      "Requirement already satisfied: scipy in c:\\users\\yc\\anaconda3\\lib\\site-packages (from xgboost) (1.7.1)\n",
      "Requirement already satisfied: numpy in c:\\users\\yc\\anaconda3\\lib\\site-packages (from xgboost) (1.21.2)\n",
      "Note: you may need to restart the kernel to use updated packages.\n"
     ]
    }
   ],
   "source": [
    "pip install xgboost"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "随机森林准确率\n",
      "[[14  4]\n",
      " [ 3  8]]\n",
      "              precision    recall  f1-score   support\n",
      "\n",
      "           0       0.82      0.78      0.80        18\n",
      "           1       0.67      0.73      0.70        11\n",
      "\n",
      "    accuracy                           0.76        29\n",
      "   macro avg       0.75      0.75      0.75        29\n",
      "weighted avg       0.76      0.76      0.76        29\n",
      "\n",
      "0.7586206896551724\n",
      "模型得分:0.76\n",
      "随机森林预测结果： [0 0 0 1 0 1 1 1 1 0 0 1 1 1 0 0 0 1 0 0 1 0 0 1 0 0 1 0 0]\n",
      "真实结果:          [0 0 0 1 0 0 1 1 0 1 0 1 1 0 0 0 0 1 0 0 1 1 1 1 0 0 0 0 0]\n",
      "-------------------------------------------\n"
     ]
    }
   ],
   "source": [
    "#   训练数据(随机森林)\n",
    "def random_forest():\n",
    "    #   将数据标准化\n",
    "    X = df.drop('Outcome', axis=1)\n",
    "    # 一共768个数据738个作为训练集，30个作为测试集\n",
    "    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=30 / 768, random_state=0)\n",
    "    # 若数值过大可以标准化，这里数值不算大，标准化后准确值较低，所以注释掉了不进行标准化\n",
    "    # sc = StandardScaler()\n",
    "    # X_train = sc.fit_transform(X_train)\n",
    "    # X_test = sc.transform(X_test)\n",
    "    classifier = RandomForestClassifier(criterion='entropy', n_estimators=1000, max_depth=None, min_samples_split=10,\n",
    "                                        min_weight_fraction_leaf=0.02)\n",
    "    classifier.fit(X_train, y_train)\n",
    "    y_pred = classifier.predict(X_test)\n",
    "    print('随机森林准确率')\n",
    "    print(confusion_matrix(y_test, y_pred))\n",
    "    print(classification_report(y_test, y_pred))\n",
    "    print(accuracy_score(y_test, y_pred))\n",
    "    print('模型得分:{:.2f}'.format(classifier.score(X_test, y_test)))\n",
    "    y_ = np.array(y_test)\n",
    "    print('随机森林预测结果：', classifier.predict(X_test))\n",
    "    print('真实结果:         ', y_)\n",
    "    print('-------------------------------------------')\n",
    "if __name__ == '__main__':\n",
    "    random_forest()\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "决策树准确率\n",
      "[[14  3]\n",
      " [ 6  6]]\n",
      "              precision    recall  f1-score   support\n",
      "\n",
      "           0       0.70      0.82      0.76        17\n",
      "           1       0.67      0.50      0.57        12\n",
      "\n",
      "    accuracy                           0.69        29\n",
      "   macro avg       0.68      0.66      0.66        29\n",
      "weighted avg       0.69      0.69      0.68        29\n",
      "\n",
      "0.6896551724137931\n",
      "模型得分:0.69\n",
      "决策树预测结果： [1 0 1 0 1 0 1 0 0 1 0 0 1 0 0 0 0 0 0 0 1 0 1 0 1 0 0 0 0]\n",
      "真实结果:          [0 0 1 0 1 1 1 0 0 1 0 0 0 1 0 0 0 1 0 0 0 0 1 1 1 0 1 1 0]\n",
      "--------------------------------------------------------------------------------------\n"
     ]
    }
   ],
   "source": [
    "#   训练数据（决策树）\n",
    "def decision_tree():\n",
    "    X = df.drop('Outcome', axis=1)\n",
    "    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=30 / 768)\n",
    "    # 参数是经过测试得到的最高准确率的参数\n",
    "    classifier = DecisionTreeClassifier(criterion='entropy', max_depth=3, min_weight_fraction_leaf=0.01)\n",
    "    classifier.fit(X_train, y_train)\n",
    "    y_pred = classifier.predict(X_test)\n",
    "    print('决策树准确率')\n",
    "    print(confusion_matrix(y_test, y_pred))\n",
    "    print(classification_report(y_test, y_pred))\n",
    "    print(accuracy_score(y_test, y_pred))\n",
    "    print('模型得分:{:.2f}'.format(classifier.score(X_test, y_test)))\n",
    "    y_ = np.array(y_test)\n",
    "    print('决策树预测结果：', classifier.predict(X_test))\n",
    "    print('真实结果:         ', y_)\n",
    "    print('--------------------------------------------------------------------------------------')\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    decision_tree()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "逻辑回归准确率\n",
      "[[16  2]\n",
      " [ 3  8]]\n",
      "              precision    recall  f1-score   support\n",
      "\n",
      "           0       0.84      0.89      0.86        18\n",
      "           1       0.80      0.73      0.76        11\n",
      "\n",
      "    accuracy                           0.83        29\n",
      "   macro avg       0.82      0.81      0.81        29\n",
      "weighted avg       0.83      0.83      0.83        29\n",
      "\n",
      "0.8275862068965517\n",
      "模型得分:0.83\n",
      "逻辑回归预测结果： [0 0 0 1 0 0 0 1 0 0 0 1 1 1 0 0 0 1 0 0 1 0 1 1 0 0 1 0 0]\n",
      "真实结果:          [0 0 0 1 0 0 1 1 0 1 0 1 1 0 0 0 0 1 0 0 1 1 1 1 0 0 0 0 0]\n",
      "--------------------------------------------------------------------------------------\n"
     ]
    }
   ],
   "source": [
    "#   训练数据（逻辑回归）\n",
    "def logistic_regression():\n",
    "    X = df.drop('Outcome', axis=1)\n",
    "    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=30 / 768, random_state=0)\n",
    "    # sc = StandardScaler()\n",
    "    # X_train = sc.fit_transform(X_train)\n",
    "    # X_test = sc.transform(X_test)\n",
    "    lr = LogisticRegression(random_state=0, max_iter=1000)\n",
    "    lr.fit(X_train, y_train)\n",
    "    y_pred = lr.predict(X_test)\n",
    "    print('逻辑回归准确率')\n",
    "    print(confusion_matrix(y_test, y_pred))\n",
    "    print(classification_report(y_test, y_pred))\n",
    "    print(accuracy_score(y_test, y_pred))\n",
    "    print('模型得分:{:.2f}'.format(lr.score(X_test, y_test)))\n",
    "    y_ = np.array(y_test)\n",
    "    print('逻辑回归预测结果：', lr.predict(X_test))\n",
    "    print('真实结果:         ', y_)\n",
    "    print('--------------------------------------------------------------------------------------')\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    logistic_regression()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "当k= 1 时的准确率\n",
      "[[13  5]\n",
      " [ 4  7]]\n",
      "              precision    recall  f1-score   support\n",
      "\n",
      "           0       0.76      0.72      0.74        18\n",
      "           1       0.58      0.64      0.61        11\n",
      "\n",
      "    accuracy                           0.69        29\n",
      "   macro avg       0.67      0.68      0.68        29\n",
      "weighted avg       0.70      0.69      0.69        29\n",
      "\n",
      "模型得分:0.69\n",
      "当k= 2 时的准确率\n",
      "[[17  1]\n",
      " [ 8  3]]\n",
      "              precision    recall  f1-score   support\n",
      "\n",
      "           0       0.68      0.94      0.79        18\n",
      "           1       0.75      0.27      0.40        11\n",
      "\n",
      "    accuracy                           0.69        29\n",
      "   macro avg       0.72      0.61      0.60        29\n",
      "weighted avg       0.71      0.69      0.64        29\n",
      "\n",
      "模型得分:0.69\n",
      "当k= 3 时的准确率\n",
      "[[13  5]\n",
      " [ 6  5]]\n",
      "              precision    recall  f1-score   support\n",
      "\n",
      "           0       0.68      0.72      0.70        18\n",
      "           1       0.50      0.45      0.48        11\n",
      "\n",
      "    accuracy                           0.62        29\n",
      "   macro avg       0.59      0.59      0.59        29\n",
      "weighted avg       0.61      0.62      0.62        29\n",
      "\n",
      "模型得分:0.62\n",
      "当k= 4 时的准确率\n",
      "[[15  3]\n",
      " [ 8  3]]\n",
      "              precision    recall  f1-score   support\n",
      "\n",
      "           0       0.65      0.83      0.73        18\n",
      "           1       0.50      0.27      0.35        11\n",
      "\n",
      "    accuracy                           0.62        29\n",
      "   macro avg       0.58      0.55      0.54        29\n",
      "weighted avg       0.59      0.62      0.59        29\n",
      "\n",
      "模型得分:0.62\n",
      "当k= 5 时的准确率\n",
      "[[12  6]\n",
      " [ 4  7]]\n",
      "              precision    recall  f1-score   support\n",
      "\n",
      "           0       0.75      0.67      0.71        18\n",
      "           1       0.54      0.64      0.58        11\n",
      "\n",
      "    accuracy                           0.66        29\n",
      "   macro avg       0.64      0.65      0.64        29\n",
      "weighted avg       0.67      0.66      0.66        29\n",
      "\n",
      "模型得分:0.66\n",
      "当k= 6 时的准确率\n",
      "[[15  3]\n",
      " [ 7  4]]\n",
      "              precision    recall  f1-score   support\n",
      "\n",
      "           0       0.68      0.83      0.75        18\n",
      "           1       0.57      0.36      0.44        11\n",
      "\n",
      "    accuracy                           0.66        29\n",
      "   macro avg       0.63      0.60      0.60        29\n",
      "weighted avg       0.64      0.66      0.63        29\n",
      "\n",
      "模型得分:0.66\n",
      "当k= 7 时的准确率\n",
      "[[14  4]\n",
      " [ 5  6]]\n",
      "              precision    recall  f1-score   support\n",
      "\n",
      "           0       0.74      0.78      0.76        18\n",
      "           1       0.60      0.55      0.57        11\n",
      "\n",
      "    accuracy                           0.69        29\n",
      "   macro avg       0.67      0.66      0.66        29\n",
      "weighted avg       0.68      0.69      0.69        29\n",
      "\n",
      "模型得分:0.69\n",
      "当k= 8 时的准确率\n",
      "[[16  2]\n",
      " [ 7  4]]\n",
      "              precision    recall  f1-score   support\n",
      "\n",
      "           0       0.70      0.89      0.78        18\n",
      "           1       0.67      0.36      0.47        11\n",
      "\n",
      "    accuracy                           0.69        29\n",
      "   macro avg       0.68      0.63      0.63        29\n",
      "weighted avg       0.68      0.69      0.66        29\n",
      "\n",
      "模型得分:0.69\n",
      "当k= 9 时的准确率\n",
      "[[13  5]\n",
      " [ 5  6]]\n",
      "              precision    recall  f1-score   support\n",
      "\n",
      "           0       0.72      0.72      0.72        18\n",
      "           1       0.55      0.55      0.55        11\n",
      "\n",
      "    accuracy                           0.66        29\n",
      "   macro avg       0.63      0.63      0.63        29\n",
      "weighted avg       0.66      0.66      0.66        29\n",
      "\n",
      "模型得分:0.66\n",
      "当k= 10 时的准确率\n",
      "[[14  4]\n",
      " [ 6  5]]\n",
      "              precision    recall  f1-score   support\n",
      "\n",
      "           0       0.70      0.78      0.74        18\n",
      "           1       0.56      0.45      0.50        11\n",
      "\n",
      "    accuracy                           0.66        29\n",
      "   macro avg       0.63      0.62      0.62        29\n",
      "weighted avg       0.65      0.66      0.65        29\n",
      "\n",
      "模型得分:0.66\n",
      "当k= 11 时的准确率\n",
      "[[14  4]\n",
      " [ 5  6]]\n",
      "              precision    recall  f1-score   support\n",
      "\n",
      "           0       0.74      0.78      0.76        18\n",
      "           1       0.60      0.55      0.57        11\n",
      "\n",
      "    accuracy                           0.69        29\n",
      "   macro avg       0.67      0.66      0.66        29\n",
      "weighted avg       0.68      0.69      0.69        29\n",
      "\n",
      "模型得分:0.69\n",
      "当k= 12 时的准确率\n",
      "[[16  2]\n",
      " [ 6  5]]\n",
      "              precision    recall  f1-score   support\n",
      "\n",
      "           0       0.73      0.89      0.80        18\n",
      "           1       0.71      0.45      0.56        11\n",
      "\n",
      "    accuracy                           0.72        29\n",
      "   macro avg       0.72      0.67      0.68        29\n",
      "weighted avg       0.72      0.72      0.71        29\n",
      "\n",
      "模型得分:0.72\n",
      "当k= 13 时的准确率\n",
      "[[15  3]\n",
      " [ 5  6]]\n",
      "              precision    recall  f1-score   support\n",
      "\n",
      "           0       0.75      0.83      0.79        18\n",
      "           1       0.67      0.55      0.60        11\n",
      "\n",
      "    accuracy                           0.72        29\n",
      "   macro avg       0.71      0.69      0.69        29\n",
      "weighted avg       0.72      0.72      0.72        29\n",
      "\n",
      "模型得分:0.72\n",
      "当k= 14 时的准确率\n",
      "[[16  2]\n",
      " [ 6  5]]\n",
      "              precision    recall  f1-score   support\n",
      "\n",
      "           0       0.73      0.89      0.80        18\n",
      "           1       0.71      0.45      0.56        11\n",
      "\n",
      "    accuracy                           0.72        29\n",
      "   macro avg       0.72      0.67      0.68        29\n",
      "weighted avg       0.72      0.72      0.71        29\n",
      "\n",
      "模型得分:0.72\n"
     ]
    }
   ],
   "source": [
    "#   训练数据（KNN）寻找最佳的k值\n",
    "def k_nn():\n",
    "    X = df.drop('Outcome', axis=1)\n",
    "    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=30 / 768, random_state=0)\n",
    "    # scaler = StandardScaler()\n",
    "    # scaler.fit(X_train)\n",
    "    # x_train = scaler.transform(X_train)\n",
    "    # x_test = scaler.transform(X_test)\n",
    "    error = []\n",
    "    # 由于一开始并不清楚K取多少准确率最高，所以写了一个K为1-14的for循环，通过检查误差值来判断最合适的K值\n",
    "    for k in range(1, 15):\n",
    "        classifier = KNeighborsClassifier(n_neighbors=k)\n",
    "        classifier.fit(X_train, y_train)\n",
    "        y_prediction = classifier.predict(X_test)\n",
    "        error.append(np.mean(y_prediction != y_test))\n",
    "        print('当k=', k, '时的准确率')\n",
    "        print(confusion_matrix(y_test, y_prediction))\n",
    "        print(classification_report(y_test, y_prediction))\n",
    "        print('模型得分:{:.2f}'.format(classifier.score(X_test, y_test)))\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    k_nn()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Neural Network准确率\n",
      "[[16  2]\n",
      " [ 7  4]]\n",
      "              precision    recall  f1-score   support\n",
      "\n",
      "           0       0.70      0.89      0.78        18\n",
      "           1       0.67      0.36      0.47        11\n",
      "\n",
      "    accuracy                           0.69        29\n",
      "   macro avg       0.68      0.63      0.63        29\n",
      "weighted avg       0.68      0.69      0.66        29\n",
      "\n",
      "0.6896551724137931\n",
      "模型得分:0.69\n",
      "Neural Network预测结果： [0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 1 1 0 1 0 0]\n",
      "真实结果:          [0 0 0 1 0 0 1 1 0 1 0 1 1 0 0 0 0 1 0 0 1 1 1 1 0 0 0 0 0]\n",
      "--------------------------------------------------------------------------------------\n"
     ]
    }
   ],
   "source": [
    "#   训练数据（Neural Networks）\n",
    "def n_n():\n",
    "    X = df.drop('Outcome', axis=1)\n",
    "    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=30 / 768, random_state=0)\n",
    "    # sc = StandardScaler()\n",
    "    # X_train = sc.fit_transform(X_train)\n",
    "    # X_test = sc.transform(X_test)\n",
    "    mlp = MLPClassifier(random_state=0, max_iter=5000)\n",
    "    mlp.fit(X_train, y_train)\n",
    "    y_pred = mlp.predict(X_test)\n",
    "    print('Neural Network准确率')\n",
    "    print(confusion_matrix(y_test, y_pred))\n",
    "    print(classification_report(y_test, y_pred))\n",
    "    print(accuracy_score(y_test, y_pred))\n",
    "    print('模型得分:{:.2f}'.format(mlp.score(X_test, y_test)))\n",
    "    y_ = np.array(y_test)\n",
    "    print('Neural Network预测结果：', mlp.predict(X_test))\n",
    "    print('真实结果:         ', y_)\n",
    "    print('--------------------------------------------------------------------------------------')\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    n_n()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "XGBoost准确率\n",
      "[[13  5]\n",
      " [ 2  9]]\n",
      "              precision    recall  f1-score   support\n",
      "\n",
      "           0       0.87      0.72      0.79        18\n",
      "           1       0.64      0.82      0.72        11\n",
      "\n",
      "    accuracy                           0.76        29\n",
      "   macro avg       0.75      0.77      0.75        29\n",
      "weighted avg       0.78      0.76      0.76        29\n",
      "\n",
      "0.7586206896551724\n",
      "模型得分:0.76\n",
      "XGBoost预测结果： [0 0 0 1 1 1 1 1 1 1 0 1 1 1 0 0 0 1 0 0 1 0 1 0 0 0 1 0 0]\n",
      "真实结果:          [0 0 0 1 0 0 1 1 0 1 0 1 1 0 0 0 0 1 0 0 1 1 1 1 0 0 0 0 0]\n",
      "--------------------------------------------------------------------------------------\n"
     ]
    }
   ],
   "source": [
    "#   训练数据（XGBoost）\n",
    "def xgb():\n",
    "    X = df.drop('Outcome', axis=1)\n",
    "    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=30 / 768, random_state=0)\n",
    "    xgb = XGBClassifier(gamma=0, use_label_encoder=False, learning_rate=0.01, max_depth=10, n_estimators=10000, random_state=34, reg_lambda=6, reg_alpha=3, verbosity=0)\n",
    "    xgb.fit(X_train, y_train)\n",
    "    y_prediction = xgb.predict(X_test)\n",
    "    print('XGBoost准确率')\n",
    "    print(confusion_matrix(y_test, y_prediction))\n",
    "    print(classification_report(y_test, y_prediction))\n",
    "    print(accuracy_score(y_test, y_prediction))\n",
    "    print('模型得分:{:.2f}'.format(xgb.score(X_test, y_test)))\n",
    "    y_ = np.array(y_test)\n",
    "    print('XGBoost预测结果：', xgb.predict(X_test))\n",
    "    print('真实结果:         ', y_)\n",
    "    print('--------------------------------------------------------------------------------------')\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    xgb()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "SVM准确率\n",
      "[[17  1]\n",
      " [ 6  5]]\n",
      "              precision    recall  f1-score   support\n",
      "\n",
      "           0       0.74      0.94      0.83        18\n",
      "           1       0.83      0.45      0.59        11\n",
      "\n",
      "    accuracy                           0.76        29\n",
      "   macro avg       0.79      0.70      0.71        29\n",
      "weighted avg       0.77      0.76      0.74        29\n",
      "\n",
      "0.7586206896551724\n",
      "模型得分:0.76\n",
      "SVM预测结果： [0 0 0 1 0 0 0 1 0 0 0 1 1 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0]\n",
      "真实结果:          [0 0 0 1 0 0 1 1 0 1 0 1 1 0 0 0 0 1 0 0 1 1 1 1 0 0 0 0 0]\n",
      "--------------------------------------------------------------------------------------\n"
     ]
    }
   ],
   "source": [
    "def svm():\n",
    "    X = df.drop('Outcome', axis=1)\n",
    "    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=30 / 768, random_state=0)\n",
    "    svm = SVC(probability=True, random_state=0)\n",
    "    svm.fit(X_train, y_train)\n",
    "    y_pred = svm.predict(X_test)\n",
    "    print('SVM准确率')\n",
    "    print(confusion_matrix(y_test, y_pred))\n",
    "    print(classification_report(y_test, y_pred))\n",
    "    print(accuracy_score(y_test, y_pred))\n",
    "    print('模型得分:{:.2f}'.format(svm.score(X_test, y_test)))\n",
    "    y_ = np.array(y_test)\n",
    "    print('SVM预测结果：', svm.predict(X_test))\n",
    "    print('真实结果:         ', y_)\n",
    "    print('--------------------------------------------------------------------------------------')\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    svm()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "SVM准确率\n",
      "[[17  1]\n",
      " [ 6  5]]\n",
      "              precision    recall  f1-score   support\n",
      "\n",
      "           0       0.74      0.94      0.83        18\n",
      "           1       0.83      0.45      0.59        11\n",
      "\n",
      "    accuracy                           0.76        29\n",
      "   macro avg       0.79      0.70      0.71        29\n",
      "weighted avg       0.77      0.76      0.74        29\n",
      "\n",
      "0.7586206896551724\n",
      "模型得分:0.76\n",
      "SVM预测结果： [0 0 0 1 0 0 0 1 0 0 0 1 1 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0]\n",
      "真实结果:          [0 0 0 1 0 0 1 1 0 1 0 1 1 0 0 0 0 1 0 0 1 1 1 1 0 0 0 0 0]\n",
      "--------------------------------------------------------------------------------------\n",
      "随机森林准确率\n",
      "[[14  4]\n",
      " [ 4  7]]\n",
      "              precision    recall  f1-score   support\n",
      "\n",
      "           0       0.78      0.78      0.78        18\n",
      "           1       0.64      0.64      0.64        11\n",
      "\n",
      "    accuracy                           0.72        29\n",
      "   macro avg       0.71      0.71      0.71        29\n",
      "weighted avg       0.72      0.72      0.72        29\n",
      "\n",
      "0.7241379310344828\n",
      "模型得分:0.72\n",
      "随机森林预测结果： [0 0 0 1 0 1 1 1 1 0 0 1 1 1 0 0 0 1 0 0 1 0 0 0 0 0 1 0 0]\n",
      "真实结果:          [0 0 0 1 0 0 1 1 0 1 0 1 1 0 0 0 0 1 0 0 1 1 1 1 0 0 0 0 0]\n",
      "-------------------------------------------\n",
      "XGBoost准确率\n",
      "[[13  5]\n",
      " [ 2  9]]\n",
      "              precision    recall  f1-score   support\n",
      "\n",
      "           0       0.87      0.72      0.79        18\n",
      "           1       0.64      0.82      0.72        11\n",
      "\n",
      "    accuracy                           0.76        29\n",
      "   macro avg       0.75      0.77      0.75        29\n",
      "weighted avg       0.78      0.76      0.76        29\n",
      "\n",
      "0.7586206896551724\n",
      "模型得分:0.76\n",
      "XGBoost预测结果： [0 0 0 1 1 1 1 1 1 1 0 1 1 1 0 0 0 1 0 0 1 0 1 0 0 0 1 0 0]\n",
      "真实结果:          [0 0 0 1 0 0 1 1 0 1 0 1 1 0 0 0 0 1 0 0 1 1 1 1 0 0 0 0 0]\n",
      "--------------------------------------------------------------------------------------\n",
      "逻辑回归准确率\n",
      "[[16  2]\n",
      " [ 3  8]]\n",
      "              precision    recall  f1-score   support\n",
      "\n",
      "           0       0.84      0.89      0.86        18\n",
      "           1       0.80      0.73      0.76        11\n",
      "\n",
      "    accuracy                           0.83        29\n",
      "   macro avg       0.82      0.81      0.81        29\n",
      "weighted avg       0.83      0.83      0.83        29\n",
      "\n",
      "0.8275862068965517\n",
      "模型得分:0.83\n",
      "逻辑回归预测结果： [0 0 0 1 0 0 0 1 0 0 0 1 1 1 0 0 0 1 0 0 1 0 1 1 0 0 1 0 0]\n",
      "真实结果:          [0 0 0 1 0 0 1 1 0 1 0 1 1 0 0 0 0 1 0 0 1 1 1 1 0 0 0 0 0]\n",
      "--------------------------------------------------------------------------------------\n"
     ]
    }
   ],
   "source": [
    "#   主菜单\n",
    "def main_menu():\n",
    "    print('-' * 11, '糖尿病诊断预测', '-' * 11)\n",
    "    print('|{:20}|{:20}|'.format('1.输入指标', '2.退出系统'))\n",
    "\n",
    "\n",
    "#   选择模型菜单\n",
    "def option_menu():\n",
    "    print('-' * 12, '训练模型选择', '-' * 12)\n",
    "    print('|{:20}|{:20}|'.format('1.所有模型', '2.随机森林'))\n",
    "    print('|{:20}|{:20}|'.format('3.决策树', '4.逻辑回归'))\n",
    "    print('|{:23}|{:20}|'.format('5.KNN', '6.连接模型'))\n",
    "    print('|{:23}|{:20}|'.format('7.XGBoost', '8.SVM'))\n",
    "\n",
    "\n",
    "#   登出\n",
    "def logout():\n",
    "    print('感谢使用')\n",
    "if __name__ == '__main__':\n",
    "    while True:\n",
    "        main_menu()\n",
    "        key = input('请输入你的选择: ')\n",
    "        if key == '1':\n",
    "            try:\n",
    "                Pregnancy = float(input('输入怀孕指数：'))\n",
    "                Glu = float(input('输入葡萄糖指数：'))\n",
    "                BP = float(input('输入血压：'))\n",
    "                ST = float(input('输入皮肤厚度：'))\n",
    "                Ins = float(input('输入胰岛素指数：'))\n",
    "                BMI = float(input('输入体质指数：'))\n",
    "                DBF = float(input('输入糖尿病谱系功能指数：'))\n",
    "                Age = float(input('输入年龄：'))\n",
    "            except:\n",
    "                print(\"不符合输入要求，请重新输入\")\n",
    "                continue\n",
    "\t\t\t# 将输入的值放在一个列表中\n",
    "            indices = [Pregnancy, Glu, BP, ST, Ins, BMI, DBF, Age]\n",
    "            l = []\n",
    "            for index in indices:\n",
    "                l.append(index)\n",
    "\n",
    "            empty_indices = {\"Pregnancies\": l[0], \"Glucose\": l[1], \"BloodPressure\": l[2], \"SkinThickness\": l[3], \"Insulin\": l[4], \"BMI\": l[5], \"DiabetesPedigreeFunction\": l[6], \"Age\": l[7]}\n",
    "            data = pd.DataFrame(empty_indices, index=[0])\n",
    "            data = data.set_index('Pregnancies')\n",
    "            data.to_csv(\"new.csv\")\n",
    "            df_1 = pd.read_csv(\"new.csv\")\n",
    "            s = df_1.iloc[0]\n",
    "            # 选择模型菜单\n",
    "            option_menu()\n",
    "            option = input('请选择模型：')\n",
    "            #   显示所有的训练模型结果\n",
    "            if option == '1':\n",
    "                random_forest()\n",
    "                decision_tree()\n",
    "                logistic_regression()\n",
    "                k_nn()\n",
    "                n_n()\n",
    "                xgb()\n",
    "                svm()\n",
    "            elif option == '2':\n",
    "                random_forest()\n",
    "            elif option == '3':\n",
    "                decision_tree()\n",
    "            elif option == '4':\n",
    "                logistic_regression()\n",
    "            elif option == '5':\n",
    "                k_nn()\n",
    "            elif option == '6':\n",
    "                n_n()\n",
    "            elif option == '7':\n",
    "                xgb()\n",
    "            elif option == '8':\n",
    "                svm()\n",
    "            else:\n",
    "                print('无效输入')\n",
    "                continue\n",
    "        elif key == '2':\n",
    "            logout()\n",
    "            break\n",
    "        else:\n",
    "            print('无效输入')\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 选择最优模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def BuidModel():\n",
    "    svm()\n",
    "    random_forest()\n",
    "    xgb()\n",
    "    logistic_regression()\n",
    "if __name__ == '__main__':\n",
    "    BuidModel()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
